<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2018/11/18
 * Time: 14:16
 */
namespace common\services;

use Yii;
use yii\db\Exception;
use common\services\HttpUploadService;

use common\models\city\CityCode;
use common\models\weather\Weather;


class GeographyService
{
    public function __construct()
    {
        // 高德
        $this->lbcConfig       =       Yii::$app->params['lbs'];
        $this->lbcKey          =       Yii::$app->params['lbs']['key'];
        $this->lbcIpApi        =       Yii::$app->params['lbs']['ipApi'];
        $this->lbcGeocode      =       Yii::$app->params['lbs']['geocode'];
        $this->lbcWeatherApi   =       Yii::$app->params['lbs']['weatherApi'];

        // 百度
        $this->baiduConfig     =       Yii::$app->params['baidu'];
        $this->baiduKey        =       Yii::$app->params['baidu']['key'];
        $this->baiduIpApi      =       Yii::$app->params['baidu']['ipApi'];

    }

    /**
     * 获取访问者IP
     * @return mixed
     */
    public function httpClientIp()
    {
        return $_SERVER["REMOTE_ADDR"];
    }

    /**
     * 根据ip获取城市code
     * @return mixed|string
     */
    public function adcode()
    {
        $result = $this->ipAddress();
        $adcode = '100000';
        if (!empty($result)) {
            $result = json_decode($result);
            if (!empty($result->status) && $result->status == 1) {
                $adcode = $result->adcode;
            }
        }
        return $adcode;
    }

    /**
     * 获取ip地址信息
     * @param string $ip
     * @param string $output
     * @return array|mixed
     */
    public function ipAddress($ip = '', $output = 'JSON')
    {
        $key = $this->lbcKey;
        $url = $this->lbcIpApi;
        if (empty($ip)) {
            $ip = $this->httpClientIp();
        }
        $ipUrl = $url . '?ip=' . $ip . '&output=' . $output . '&key=' . $key;
        try {
            $result = HttpUploadService::curlRequest($ipUrl);
        } catch (\Exception $e) {
            $result = [];
        }
        return $result;
    }

    /**
     * 根据城市code获取天气信息
     * @param string $cityId
     * @param string $output
     * @return array|mixed
     */
    public function weather($cityId = '110000', $output = 'JSON')
    {
        $key = $this->lbcKey;
        $url = $this->lbcWeatherApi;

        $weatherUrl = $url . '?key=' . $key . '&city=' . $cityId . '&output=' . $output;
        try {
            $result = HttpUploadService::curlRequest($weatherUrl);
        } catch (\Exception $e) {
            $result = [];
        }
        return $result;
    }

    /**
     *  查询天气信息
     * @param string $adcode    城市编码
     * @return array|null|\yii\db\ActiveRecord
     */
    public function findOneWeather($adcode = '')
    {
        $reslut = Weather::find()
            ->where(['adcode' => $adcode])
            ->andWhere(['date' => date('Y-m-d H').':00:00'])
            ->select('province, city, adcode, weather, temperature, winddirection, windpower, humidity, date')
            ->orderBy('id DESC')
            ->limit(1)
            ->asArray()
            ->one();
        return $reslut;
    }

    /**
     * 入库操作
     * @param $result
     * @return array|Weather
     */
    public function saveWeather($result)
    {
        $array = [];
        if (empty($result))  return $array;

        // json转换高德返回数据
        $weather = json_decode($result);
        // 验证数据
        if (!is_object($weather))           return $array;
        if ($weather->status == 0)          return $array;
        if (empty($weather->lives) ||
            !is_array($weather->lives) ||
            !is_object($weather->lives[0])) return $array;
        $info = $weather->lives[0];
        $weatherModel = new Weather();
        $weatherModel->province      = $info->province;
        $weatherModel->city          = $info->city;
        $weatherModel->adcode        = $info->adcode;
        $weatherModel->weather       = $info->weather;
        $weatherModel->temperature   = $info->temperature;
        $weatherModel->winddirection = $info->winddirection;
        $weatherModel->windpower     = $info->windpower;
        $weatherModel->humidity      = $info->humidity;
        $weatherModel->reporttime    = $info->reporttime;
        $weatherModel->date          = date('Y-m-d H').':00:00';
        if ($weatherModel->save()) {
            return Weather::find()
                ->where(['adcode' => $info->adcode])
                ->andWhere(['date' => date('Y-m-d H').':00:00'])
                ->select('province, city, adcode, weather, temperature, winddirection, windpower, humidity, date')
                ->orderBy('id DESC')
                ->limit(1)
                ->asArray()
                ->one();
        }
        return $array;
    }

    /**
     * 模糊匹配code查询天气
     * @param $city
     * @return array|\yii\db\ActiveRecord[]
     */
    public function cityCode($city)
    {
        $result = CityCode::find()
            ->where("city like :keywords")
            ->addParams([':keywords' => '%' . $city . '%'])
            ->andWhere(['!=', 'citycode', ''])
            ->orderBy('id DESC')
            ->limit(5)
            ->all();
        return $result;
    }
}